/* board.c */

#include <stdio.h>

#include "board.h"
#include "clock_config.h"

#include "fsl_clock.h"
#include "fsl_uart.h"

static void stdio_init(void);

void board_init(void)
{
    BOARD_BootClockRUN();

    stdio_init();
}

void stdio_init(void)
{
    /* pins. */
    CLOCK_EnableClock(kCLOCK_PortA);
    PORTA->PCR[1] = PORT_PCR_MUX(2); /* PTA1, UART0_RX. */
    PORTA->PCR[2] = PORT_PCR_MUX(2); /* PTA2, UART0_TX. */

    /* clocks. */
    SIM->SOPT2 = (SIM->SOPT2 & ~SIM_SOPT2_UART0SRC_MASK)
               | SIM_SOPT2_UART0SRC(1)
               | SIM_SOPT2_PLLFLLSEL_MASK;
    CLOCK_EnableClock(kCLOCK_Uart0);

    /* controller. */
    UART0->C2 = 0u; /* disble the transfer before any setting. */
    uint32_t div = CLOCK_GetFreq(kCLOCK_PllFllSelClk) / BOARD_STDIO_UART_BAUDRAGE / 16u;
    UART0->BDL = (uint8_t)(0xff & div);
    UART0->BDH = (uint8_t)(0xff & (div >> 8u));
    UART0->C1  = 0u;
    UART0->S1  = UART0->S1; /* clear flags. */
    UART0->C2  = UART_C2_TE_MASK /* enable tx. */
               | UART_C2_RE_MASK /* enable rx. */
               ;
}

int fputc(int ch, FILE *f)
{
	uint8_t tmp8 = (uint8_t)ch;

    while ( !(UART0->S1 & UART_S1_TDRE_MASK) )
    {}
    UART0->D = tmp8;

 	return ch;
}

int fgetc(FILE *f)
{
	while ( !(UART0->S1 & UART_S1_RDRF_MASK) )
    {}
    uint8_t tmp8 = UART0->D;

	return tmp8;
}

/* EOF. */

